/* Task Manager JavaScript
   - Stores tasks in localStorage
   - Allows add, delete, toggle complete
   - Accessible announcements using aria-live
*/
(function(){
  'use strict';
  // create filter UI and matching styles so filter-buttons exist for the rest of the script
  (function(){
    const formEl = document.getElementById('task-form');

    // Insert minimal styles that match the simple existing design
    const style = document.createElement('style');
    style.textContent = `
      .filters { display:flex; gap:8px; margin:10px 0; align-items:center; }
      .filter-btn {
        -webkit-appearance:none;
        appearance:none;
        border:1px solid #e0e0e0;
        background:#fafafa;
        color:#222;
        padding:6px 10px;
        border-radius:6px;
        cursor:pointer;
        font-size:0.95rem;
      }
      .filter-btn[aria-pressed="true"] {
        background:#0078d4;
        color:#fff;
        border-color:#005a9e;
        box-shadow:0 1px 0 rgba(0,0,0,0.05);
      }
      .filter-btn:focus {
        outline:2px solid rgba(0,120,212,0.25);
        outline-offset:2px;
      }
      /* visually-hidden helper for screen-reader only elements used elsewhere */
      .sr-only { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px); white-space: nowrap; }
    `;
    document.head.appendChild(style);

    // Build filter toolbar with three buttons: All, Active, Completed
    const toolbar = document.createElement('div');
    toolbar.className = 'filters';
    toolbar.setAttribute('role', 'toolbar');
    toolbar.setAttribute('aria-label', 'Filter tasks');

    const filters = [
      { label: 'All', key: 'all' },
      { label: 'Active', key: 'active' },
      { label: 'Completed', key: 'completed' }
    ];

    filters.forEach((f, i) => {
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'filter-btn';
      btn.dataset.filter = f.key;
      btn.textContent = f.label;
      btn.title = `Show ${f.label.toLowerCase()} tasks`;
      // default to "all" pressed
      btn.setAttribute('aria-pressed', i === 0 ? 'true' : 'false');
      toolbar.appendChild(btn);
    });

    // Insert toolbar just after the form if present, otherwise prepend to body
    if (formEl && formEl.parentNode) {
      formEl.parentNode.insertBefore(toolbar, formEl.nextSibling);
    } else {
      document.body.insertBefore(toolbar, document.body.firstChild);
    }
  })();
  const STORAGE_KEY = 'tasks:v1';
  const THEME_KEY = 'theme:v1';

  const form = document.getElementById('task-form');
  const input = document.getElementById('task-input');
  const list = document.getElementById('task-list');
  const empty = document.getElementById('empty');
  const clearCompletedBtn = document.getElementById('clear-completed');
  const clearAllBtn = document.getElementById('clear-all');
  const filterButtons = document.querySelectorAll('.filter-btn');
  const themeToggle = document.getElementById('theme-toggle');

  let currentFilter = 'all';
  let uiTheme = 'light';

  let tasks = [];

  function save(){
    try{
      localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
    }catch(e){
      // Fail silently; localStorage may be disabled
      console.warn('Could not save tasks', e);
    }
  }

  /* Theme handling */
  function applyTheme(theme){
    uiTheme = theme === 'dark' ? 'dark' : 'light';
    try{
      if(uiTheme === 'dark'){
        document.body.classList.add('dark');
      } else {
        document.body.classList.remove('dark');
      }
      if(themeToggle) {
        themeToggle.setAttribute('aria-pressed', uiTheme === 'dark' ? 'true' : 'false');
        themeToggle.textContent = uiTheme === 'dark' ? '☀️' : '🌙';
      }
      localStorage.setItem(THEME_KEY, uiTheme);
    }catch(e){
      // ignore
    }
  }

  function loadTheme(){
    try{
      const saved = localStorage.getItem(THEME_KEY);
      if(saved) {
        applyTheme(saved);
        return;
      }
      // fallback to prefers-color-scheme
      const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
      applyTheme(prefersDark ? 'dark' : 'light');
    }catch(e){
      // ignore
    }
  }

  function load(){
    try{
      const raw = localStorage.getItem(STORAGE_KEY);
      tasks = raw ? JSON.parse(raw) : [];
    }catch(e){
      tasks = [];
    }
  }

  function createTaskElement(task){
    const li = document.createElement('li');
    li.className = 'task-item';
    li.dataset.id = task.id;
    if(task.completed) li.classList.add('completed');

    // checkbox
    const toggle = document.createElement('button');
    toggle.className = 'small-btn';
    toggle.setAttribute('aria-pressed', String(!!task.completed));
    toggle.setAttribute('aria-label', task.completed ? 'Mark as not completed' : 'Mark as completed');
    toggle.title = task.completed ? 'Undo' : 'Complete';
    toggle.innerHTML = task.completed ? '✓' : '○';
    toggle.addEventListener('click', ()=>{
      toggleComplete(task.id);
    });

    // title
    const titleWrap = document.createElement('div');
    titleWrap.className = 'title';
    const titleBtn = document.createElement('button');
    titleBtn.type = 'button';
    titleBtn.textContent = task.title;
    titleBtn.addEventListener('click', ()=>{
      toggleComplete(task.id);
    });
    titleWrap.appendChild(titleBtn);

    // meta (delete)
    const meta = document.createElement('div');
    meta.className = 'meta';
    const del = document.createElement('button');
    del.className = 'small-btn';
    del.setAttribute('aria-label','Delete task');
    del.title = 'Delete';
    del.textContent = '✕';
    del.addEventListener('click', ()=>{
      deleteTask(task.id);
    });

    meta.appendChild(del);

    li.appendChild(toggle);
    li.appendChild(titleWrap);
    li.appendChild(meta);

    return li;
  }

  function render(){
    list.innerHTML = '';
    // determine filtered tasks
    const filtered = tasks.filter(t => {
      if(currentFilter === 'all') return true;
      if(currentFilter === 'active') return !t.completed;
      if(currentFilter === 'completed') return t.completed;
      return true;
    });

    if(tasks.length === 0){
      empty.textContent = 'No tasks yet. Add your first task above.';
      empty.style.display = '';
    } else if(filtered.length === 0){
      empty.textContent = 'No tasks match this filter.';
      empty.style.display = '';
    } else {
      empty.style.display = 'none';
    }

    filtered.forEach(task => {
      list.appendChild(createTaskElement(task));
    });
  }

  function addTask(title){
    const t = { id: String(Date.now()) + Math.random().toString(36).slice(2,6), title: title.trim(), completed:false };
    tasks.unshift(t);
    save();
    render();
    announce('Task added: ' + t.title);
  }

  function toggleComplete(id){
    const idx = tasks.findIndex(t=>t.id===id);
    if(idx === -1) return;
    tasks[idx].completed = !tasks[idx].completed;
    save();
    render();
    announce(tasks[idx].completed ? 'Task completed: ' + tasks[idx].title : 'Task marked active: ' + tasks[idx].title);
  }

  function deleteTask(id){
    const idx = tasks.findIndex(t=>t.id===id);
    if(idx === -1) return;
    const removed = tasks.splice(idx,1)[0];
    save();
    render();
    announce('Task removed: ' + removed.title);
  }

  function clearCompleted(){
    const before = tasks.length;
    tasks = tasks.filter(t=>!t.completed);
    if(tasks.length === before) return; // nothing removed
    save();
    render();
    announce('Cleared completed tasks');
  }

  function clearAll(){
    if(!confirm('Clear all tasks?')) return;
    tasks = [];
    save();
    render();
    announce('All tasks cleared');
  }

  function setFilter(f){
    if(!f) return;
    currentFilter = f;
    // update aria-pressed on buttons
    filterButtons.forEach(btn => {
      btn.setAttribute('aria-pressed', btn.dataset.filter === f ? 'true' : 'false');
    });
    render();
    announce('Filter: ' + (f === 'all' ? 'All' : f === 'active' ? 'Active' : 'Completed'));
  }

  // Simple aria-live announcer
  let liveEl = null;
  function ensureLive(){
    if(liveEl) return liveEl;
    liveEl = document.createElement('div');
    liveEl.setAttribute('aria-live','polite');
    liveEl.className = 'sr-only';
    document.body.appendChild(liveEl);
    return liveEl;
  }

  function announce(msg){
    const el = ensureLive();
    el.textContent = '';
    // small timeout to ensure SR reads updates
    setTimeout(()=>{ el.textContent = msg; }, 100);
  }

  // Events
  form.addEventListener('submit', function(e){
    e.preventDefault();
    const val = input.value || '';
    if(!val.trim()){
      input.focus();
      return;
    }
    addTask(val);
    form.reset();
    input.focus();
  });

  clearCompletedBtn.addEventListener('click', clearCompleted);
  clearAllBtn.addEventListener('click', clearAll);

  // filter buttons
  filterButtons.forEach(btn => {
    btn.addEventListener('click', ()=> setFilter(btn.dataset.filter));
  });

  // theme toggle
  if(themeToggle){
    themeToggle.addEventListener('click', ()=>{
      const next = uiTheme === 'dark' ? 'light' : 'dark';
      applyTheme(next);
      announce(next === 'dark' ? 'Dark mode enabled' : 'Light mode enabled');
    });
  }

  // keyboard shortcuts: Enter on focused list item will toggle using button already; global 'n' focuses input
  document.addEventListener('keydown', (e)=>{
    if(e.key === 'n' && (document.activeElement === document.body || document.activeElement === document.documentElement)){
      input.focus();
    }
  });

  // init
  load();
  loadTheme();
  render();

})();
function sayHello(name) {
    console.log("Hello, World! " + name);
}